﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Telepathy;
using Telepathy.NetworkBase;
using Telepathy.Protocols;
using UnityEngine;

namespace Telepathy.Servers
{
    public class ServerManager : BaseTcp
    {

        protected override void Awake()
        {
            base.Awake();
            loginManager = new LoginController(this);
        }

        private void Start()
        {
            StartServer(this.Port);
            server.MaxMessageSize = 1024 * 1024;
        }

        protected override void OnConnected(Message msg)
        {
            Debug.LogWarning(string.Format("客户端连接! id:{0}", msg.connectionId));
        }

        protected override void OnDisconnected(Message msg)
        {
            Debug.LogWarning(string.Format("客户端断开! id:{0}", msg.connectionId));
        }

        protected override void OnRecvMessage(int connID, Telepathy.Protocols.MyMessage msg)
        {
            Debug.LogWarning(string.Format("收到来自 {0} 客户端消息, 类型:{1} 内容:{2}", connID, msg.MsgBase.headerType, msg.MsgBase.text));
        }

        protected override void OnLoginMessage(int connID, Protocols.LoginMessage msg)
        {
            base.OnLoginMessage(connID, msg);
			Debug.LogWarning(string.Format("客户端登录操作! id:{0}", msg.connectionId));
        }

        protected override void OnHeardMessage(int connID, Protocols.HeartMessage msg)
        {
            base.OnHeardMessage(connID, msg);
            Debug.LogWarning(string.Format("收到心跳消息:{0}", msg.MsgBase.text));
            SendMsg(connID, msg.MsgBase.text, HeaderType.Heart); //直接返回心跳消息
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="headerType"></param>
        /// <returns></returns>
        public bool SendMsg(int clientID, string strMsg, HeaderType headerType = HeaderType.Content, byte[] bytes = null)
        {
            MessageBase myMsg = GetMessageBase(strMsg, bytes, headerType);
            myMsg.messageId = MsgStringId;
            return SendToClient(clientID, myMsg.Serialize());
        }

        /// <summary>
        /// 转发使用
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="myMsg"></param>
        /// <returns></returns>
        public bool RelaySend(int clientID, MessageBase myMsg)
        {
            return SendToClient(clientID, myMsg.Serialize());
        }
    }
}